import 'package:color_dart/RgbaColor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk_example/components/a_button/index.dart';
import 'package:im_flutter_sdk_example/components/labels/index.dart';
import 'package:im_flutter_sdk_example/jsonserialize/active/data.dart';
import 'package:im_flutter_sdk_example/jsonserialize/expert/home_data.dart';
import 'package:im_flutter_sdk_example/jsonserialize/message/data.dart';
import 'package:im_flutter_sdk_example/jsonserialize/need/data.dart';
import 'package:im_flutter_sdk_example/jsonserialize/project/data.dart';
import 'package:im_flutter_sdk_example/jsonserialize/recommend/news.dart';
import 'package:im_flutter_sdk_example/jsonserialize/serve/data.dart';
import 'package:im_flutter_sdk_example/pages/activity/widgets/home_active_item.dart';
import 'package:im_flutter_sdk_example/pages/serve/widgets/home_serve_Item.dart';
import 'package:im_flutter_sdk_example/provider/group_message.dart';
import 'package:im_flutter_sdk_example/utils/event_bus.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:provider/provider.dart';
import 'package:simple_html_css/simple_html_css.dart';
import 'package:im_flutter_sdk_example/utils/screen.dart';
import 'news_item.dart';

import 'package:pull_to_refresh/pull_to_refresh.dart';

class RecommendList extends StatefulWidget {
  RecommendList({Key key}) : super(key: key);

  @override
  _RecommendListState createState() => _RecommendListState();
}

class _RecommendListState extends State<RecommendList>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  var projectData = [];
  List<ServeData> serviceData = [];
  List<NewsData> serviceNews = [];
  List<NewsData> demandNews = [];
  List<NeedData> demandData = [];
  List<ActiveData> activityData = [];
  List<NewsData> projectNews = [];
  List<HomeExpertData> expertData = [];
  List<NewsData> expertNews = [];
  List<NewsData> activityNews = [];

  List<NewsData> recommendMoreNewsData = [];
  int moreNewsOffset = 1;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: SmartRefresher(
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        header: G.pullToRefreshStyle.header(),
        footer: G.pullToRefreshStyle.footer(),
        // header: WaterDropHeader(),
        enablePullUp: true,
        child: SingleChildScrollView(
          child: Container(
            color: Colors.white,
            child: Column(children: [
              GroupNotice(),
              LabelMoreHead(
                  address: 'lib/assets/images/label/project_label.png'),
              Container(
                height: 176,
                width: double.infinity,
                padding: EdgeInsets.fromLTRB(17, 0, 17, 0),
                child: ListView(
                    //设置水平方向排列
                    scrollDirection: Axis.horizontal,
                    children: projectData
                        .map((e) => HomeProjectItem(item: e))
                        .toList()),
              ),
              Container(
                child: Column(
                    children: projectNews.map((e) {
                  if (e.fileUrls.length == 0) {
                    return NewsTextItem(item: e);
                  } else if (e.fileUrls.length == 1 || e.fileUrls.length == 2) {
                    return NewsItem(item: e);
                  } else {
                    return NewsItemMultiPic(item: e);
                  }
                }).toList()),
              ),
              LabelMoreHead(
                  address: 'lib/assets/images/label/active_label.png'),
              Container(
                height: 225,
                padding: EdgeInsets.fromLTRB(17, 0, 17, 0),
                child: ListView(
                    //设置水平方向排列
                    scrollDirection: Axis.horizontal,
                    children: activityData
                        .map((e) => HomeActiveItem(item: e))
                        .toList()),
              ),
              Container(
                child: Column(
                    children: activityNews.map((e) {
                  if (e.fileUrls.length == 0) {
                    return NewsTextItem(item: e);
                  } else if (e.fileUrls.length == 1 || e.fileUrls.length == 2) {
                    return NewsItem(item: e);
                  } else {
                    return NewsItemMultiPic(item: e);
                  }
                }).toList()),
              ),
              LabelMoreHead(address: 'lib/assets/images/label/need_label.png'),
              Container(
                height: 151,
                padding: EdgeInsets.fromLTRB(17, 0, 17, 0),
                child: ListView(
                    //设置水平方向排列
                    scrollDirection: Axis.horizontal,
                    children:
                        demandData.map((e) => HomeNeedItem(item: e)).toList()),
              ),
              Container(
                child: Column(
                    children: demandNews.map((e) {
                  if (e.fileUrls.length == 0) {
                    return NewsTextItem(item: e);
                  } else if (e.fileUrls.length == 1 || e.fileUrls.length == 2) {
                    return NewsItem(item: e);
                  } else {
                    return NewsItemMultiPic(item: e);
                  }
                }).toList()),
              ),
              LabelMoreHead(
                  address: 'lib/assets/images/label/expert_label.png'),
              Container(
                height: 192,
                padding: EdgeInsets.fromLTRB(17, 0, 17, 0),
                child: ListView(
                    //设置水平方向排列
                    scrollDirection: Axis.horizontal,
                    children: expertData
                        .map((e) => HomeExpertItem(item: e))
                        .toList()),
              ),
              Container(
                child: Column(
                    children: expertNews.map((e) {
                  if (e.fileUrls.length == 0) {
                    return NewsTextItem(item: e);
                  } else if (e.fileUrls.length == 1 || e.fileUrls.length == 2) {
                    return NewsItem(item: e);
                  } else {
                    return NewsItemMultiPic(item: e);
                  }
                }).toList()),
              ),
              LabelMoreHead(address: 'lib/assets/images/label/serve_label.png'),
              Container(
                  height: 225,
                  padding: EdgeInsets.fromLTRB(17, 0, 17, 0),
                  child: ListView(
                      //设置水平方向排列
                      scrollDirection: Axis.horizontal,
                      children: serviceData
                          .map((e) => HomeServeItem(item: e))
                          .toList())),
              Container(
                child: Column(
                    children: serviceNews.map((e) {
                  if (e.fileUrls.length == 0) {
                    return NewsTextItem(item: e);
                  } else if (e.fileUrls.length == 1 || e.fileUrls.length == 2) {
                    return NewsItem(item: e);
                  } else {
                    return NewsItemMultiPic(item: e);
                  }
                }).toList()),
              ),
              Container(
                child: Column(
                    children: recommendMoreNewsData.map((e) {
                  if (e.fileUrls.length == 0) {
                    return NewsTextItem(item: e);
                  } else if (e.fileUrls.length == 1 || e.fileUrls.length == 2) {
                    return NewsItem(item: e);
                  } else {
                    return NewsItemMultiPic(item: e);
                  }
                }).toList()),
              ),
              // MoreNewsList(),
              // LabelLoadAll()
            ]),
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _addNewsListener();
  }

  void _onRefresh() async {
    await this._reqRecommendData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await recommendMoreNews();
    _refreshController.loadComplete();
    setState(() {});
  }

  //首页数据
  Future _reqRecommendData() async {
    var res = await G.req.home.recommendList();
    if (res.data != null) {
      if (res.data['status'] != 1) return;
      var sections = res.data['data']['sections'];
      // 重置数据
      _resetData();
      sections.forEach((e) {
        if (e['title'] == 'project') {
          e['data'].forEach((e) {
            ProjectItem project = ProjectItem.fromJson(e);
            projectData.add(project);
          });
          e['news'].forEach((e) {
            NewsData pNews = NewsData.fromJson(e);
            projectNews.add(pNews);
          });
        }
        if (e['title'] == 'expert') {
          e['data'].forEach((e) {
            HomeExpertData expert = HomeExpertData.fromJson(e);
            expertData.add(expert);
          });
          e['news'].forEach((e) {
            NewsData eNews = NewsData.fromJson(e);
            expertNews.add(eNews);
          });
        }
        if (e['title'] == 'service') {
          e['data'].forEach((e) {
            ServeData serve = ServeData.fromJson(e);
            serviceData.add(serve);
          });
          e['news'].forEach((e) {
            NewsData sNews = NewsData.fromJson(e);
            serviceNews.add(sNews);
          });
        }
        if (e['title'] == 'demand') {
          e['data'].forEach((e) {
            NeedData demand = NeedData.fromJson(e);
            demandData.add(demand);
          });
          e['news'].forEach((e) {
            NewsData dNews = NewsData.fromJson(e);
            demandNews.add(dNews);
          });
        }
        if (e['title'] == 'activity') {
          e['data'].forEach((e) {
            ActiveData active = ActiveData.fromJson(e);
            activityData.add(active);
          });
          e['news'].forEach((e) {
            NewsData aNews = NewsData.fromJson(e);
            activityNews.add(aNews);
          });
        }
      });
      setState(() {});
      G.dismissLoading();
    }
    return Future;
  }

  Future recommendMoreNews() async {
    var res = await G.req.home.recommendMoreNews(moreNewsOffset);
    print("$res");
    if (res.data != null) {
      if (res.data['status'] != 1) return;
      res.data['data']['list'].forEach((e) {
        NewsData dNews = NewsData.fromJson(e);
        recommendMoreNewsData.add(dNews);
      });
      moreNewsOffset++;
    }
    return Future;
  }

  // 首页数据
  _addNewsListener() {
    eventBus.on<NewsEvent>().listen((event) {
      print("首页数据刷新");
      this._reqRecommendData();
    });
  }

  @override
  bool get wantKeepAlive => true;

  void _resetData() {
    serviceData = [];
    serviceNews = [];
    demandNews = [];
    demandData = [];
    activityData = [];
    projectNews = [];
    expertData = [];
    expertNews = [];
    activityNews = [];
    moreNewsOffset = 1;
  }
}

//小组通知
class GroupNotice extends StatelessWidget {
  const GroupNotice({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    GroupMessageProvider groupProvider =
        Provider.of<GroupMessageProvider>(context);
    if (groupProvider == null) return Container();
    Message message = groupProvider.latestMessage;
    if (message == null) return G.emptyBox();
    return Stack(
      children: [
        Container(
          height: 216.h,
          width: double.infinity,
          padding: EdgeInsets.fromLTRB(16.w, 18, 16.w, 15),
          margin: EdgeInsets.symmetric(horizontal: 16.nsp),
          // margin: EdgeInsets.fromLTRB(0, 20, 0, 25),
          decoration: BoxDecoration(
            color: rgba(247, 249, 252, 1),
            borderRadius: BorderRadius.all(Radius.circular(5)),
            image: DecorationImage(
              alignment: Alignment.topLeft,
              scale: 3.2,
              image: AssetImage("lib/assets/images/home_group_bg_left.png"),
            ),
          ),
          child: GestureDetector(
            onTap: () => {G.pushNamed('/home_message_tip')},
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                    width: 97,
                    height: 24,
                    child: Image.asset(
                        'lib/assets/images/label/groupe_notice.png')),
                Text(
                  '${message.note}',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: rgba(34, 43, 69, 0.61),
                    fontSize: 26.nsp,
                  ),
                )
              ],
            ),
          ),
        ),
        Positioned(
            right: 0,
            top: 20,
            child: SizedBox(
                width: 80,
                height: 51,
                child:
                    Image.asset('lib/assets/images/home_group_bg_right.png')))
      ],
    );
  }
}

//首页需求item
class HomeNeedItem extends StatelessWidget {
  final NeedData item;
  const HomeNeedItem({Key key, this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => {G.pushNamed('/need_detail', arguments: item)},
      child: Container(
        width: G.screenWidth() - 42,
        height: 151,
        margin: EdgeInsets.only(right: 10),
        padding: EdgeInsets.fromLTRB(18, 17, 14, 14),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(5)),
            border: Border.all(color: rgba(213, 219, 230, 0.5), width: 0.5)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.only(bottom: 13),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          color: rgba(242, 242, 242, 0.5), width: 1))),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.only(bottom: 9),
                    child: Text('${item.title}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: rgba(68, 68, 68, 1),
                            fontSize: 32.nsp,
                            fontWeight: FontWeight.w500)),
                  ),
                  Container(
                    child: RichText(
                      textAlign: TextAlign.start,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                      text: HTML.toTextSpan(
                        context,
                        item.note,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  '# ${item.keyWord}',
                  style:
                      TextStyle(color: rgba(72, 107, 157, 1), fontSize: 24.nsp),
                ),
                item.budget == '-1'
                    ? Text(
                        '面议',
                        style: TextStyle(
                            color: rgba(255, 109, 1, 1), fontSize: 34.nsp),
                      )
                    : Text(
                        '¥${item.budget}',
                        style: TextStyle(
                            color: rgba(255, 109, 1, 1), fontSize: 34.nsp),
                      )
              ],
            )
          ],
        ),
      ),
    );
  }
}

//首页项目item
class HomeProjectItem extends StatelessWidget {
  final ProjectItem item;
  const HomeProjectItem({Key key, this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => {G.pushNamed('/achievement_detail', arguments: item)},
      child: Container(
        width: (G.screenWidth() - 32.w * 2),
        height: 352.h,
        padding: EdgeInsets.fromLTRB(36.w, 32.h, 28.w, 8.h),
        margin: EdgeInsets.only(right: 20.w),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(5)),
            border: Border.all(color: rgba(213, 219, 230, 0.5), width: 0.5)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.only(bottom: 18),
              decoration: BoxDecoration(
                border: G.borderBottom(),
              ),
              child: Row(
                children: [
                  Padding(
                    padding: EdgeInsets.only(right: 13),
                    child: SizedBox(
                      width: 198.w,
                      height: 142.h,
                      child: Image.network(
                        G.fullImgPath(item.photos[0]),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Container(
                      height: 71,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${item.projectName}',
                            style: TextStyle(
                                fontSize: 32.nsp, color: rgba(68, 68, 68, 1)),
                            maxLines: 2,
                            textAlign: TextAlign.left,
                            overflow: TextOverflow.ellipsis,
                          ),
                          Row(
                            children: item.words
                                .map((e) => LabelHomeProject(name: e))
                                .toList(),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
            Text(
              '${item.yourWantContent}',
              style: TextStyle(color: rgba(107, 107, 107, 1), fontSize: 26.nsp),
              maxLines: 1,
              textAlign: TextAlign.left,
              overflow: TextOverflow.ellipsis,
            )
          ],
        ),
      ),
    );
  }
}

//专家item
class HomeExpertItem extends StatelessWidget {
  final HomeExpertData item;
  const HomeExpertItem({Key key, this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => {G.pushNamed('/expert_detail', arguments: item)},
      child: Container(
        width: (G.screenWidth() - 44) / 2,
        height: 192,
        padding: EdgeInsets.fromLTRB(0, 18, 0, 15),
        margin: EdgeInsets.only(right: 10),
        decoration: BoxDecoration(
            color: Colors.white,
            image: DecorationImage(
              alignment: Alignment.topRight,
              scale: 2,
              image: AssetImage("lib/assets/images/expert/expert-item-bg.png"),
            ),
            borderRadius: BorderRadius.all(Radius.circular(5)),
            border: Border.all(color: rgba(213, 219, 230, 0.5), width: 0.5)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(55),
                    // 圆形图片
                    image: DecorationImage(
                        image: NetworkImage('${item.photo}'),
                        fit: BoxFit.cover)),
                width: 55,
                height: 55),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  '${item.name}',
                  style: TextStyle(
                      color: rgba(68, 68, 68, 1),
                      fontSize: 17,
                      fontWeight: FontWeight.bold),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(4, 4, 0, 0),
                  child: SizedBox(
                    width: 13,
                    height: 12,
                    child: Image.asset(
                      'lib/assets/images/label/vip.png',
                      fit: BoxFit.cover,
                    ),
                  ),
                )
              ],
            ),
            Text(
              '${item.title}',
              style: TextStyle(color: rgba(107, 107, 107, 1), fontSize: 12),
            ),
            Text(
              '${item.agent}',
              style: TextStyle(color: rgba(107, 107, 107, 1), fontSize: 12),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            Padding(
                padding: EdgeInsets.only(top: 6),
                child: AButton.normal(
                    bgColor: rgba(42, 125, 250, 1),
                    width: 51,
                    height: 23,
                    onPressed: () {},
                    child: Text(
                      '问专家',
                      style: TextStyle(
                          color: rgba(255, 255, 255, 1), fontSize: 12),
                    ))),
          ],
        ),
      ),
    );
  }
}
